//
//  LXMapView.m
//  duoduo
//
//  Created by wanghao on 16/10/11.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXMapView.h"
#import "LXAnnotationView.h"
#import "UIViewExt.h"
#import "LXHomeCenterItem.h"
#import "LXDrivingLocationItem.h"

@interface LXMapView ()<MAMapViewDelegate,AMapSearchDelegate,AMapLocationManagerDelegate>
{
    LXHomeCenterItem * centerBtn_;
    CLLocationCoordinate2D coor_;
    //地图移动中心点
    CLLocationCoordinate2D mapCenterCoor_;
    LXLocation * location_;
    CLLocationCoordinate2D coor;

    NSUInteger annitationViewCount_;
    NSUInteger annitationViewCountAoutUp_;
    
}
@property(strong,nonatomic)AMapSearchAPI * search;
@property(strong,nonatomic)NSMutableArray*annotations;

@end

@implementation LXMapView

//高德定位懒加载
-(AMapLocationManager *)manager{
    if (!_manager) {
        _manager = [[AMapLocationManager alloc]init];
    }
    return _manager;
}

-(NSMutableArray*)annotations{
    //懒加载
    if (!_annotations) {
        _annotations = [NSMutableArray arrayWithCapacity:10];
    }
    return  _annotations;

}

- (id)initWithMapFrame:(CGRect)frame
{
    if (self = [super init]) {
        self.frame = frame;

        annitationViewCount_ = 0;
        annitationViewCountAoutUp_= 0 ;

        self.amapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        self.amapView.delegate = self;
        [self addSubview:_amapView];

        CGFloat bottomImageV_h = 50;
        CGFloat bottomImageV_w = 15;
        UIImageView*bottomImageV = [[UIImageView alloc]initWithFrame:CGRectMake(self.width/2-bottomImageV_w/2 ,self.height/2-bottomImageV_h, bottomImageV_w, bottomImageV_h)];
        bottomImageV.image = [UIImage imageNamed:@"dingwei@2x"];

        bottomImageV.contentMode = UIViewContentModeScaleAspectFit;
        [self addSubview:bottomImageV];

        //中间按钮
        CGFloat btn_w = 120;
        CGFloat btn_h = 40;
        LXHomeCenterItem*btn =[[LXHomeCenterItem alloc]initWithTheFram:CGRectMake(self.width/2 - btn_w/2 ,bottomImageV.top - btn_h , btn_w, btn_h) backImage:@""];
        [self addSubview:btn];
        btn.hadClickTheInsetBtnBlock = ^()
        {
            //[self clickYongChe];
        };

        centerBtn_ = btn;

//        location_ = appD.coorlocation;
//        //[location_ getTheNewLocation];
//        __weak   typeof(self) weakSelf = self;
//        location_.dingweiInfoBlock = ^(LXLocationInfoModel * locationModel)
//        {
//            //通过定位点来获取位置
//            MACoordinateSpan span = MACoordinateSpanMake(0.01, 0.01);
//            CLLocationCoordinate2D coor1 = CLLocationCoordinate2DMake([locationModel.latitude floatValue],[locationModel.latitude floatValue]);
//
//            coor_ = coor1;
//
//            MACoordinateRegion region = MACoordinateRegionMake(coor1, span);
//            [weakSelf.amapView setRegion:region];
//        };

        self.manager.delegate = self;
        //带你地理信息的一次定位
        [self.manager setDesiredAccuracy:kCLLocationAccuracyBest];
        self.manager.distanceFilter = 100;

        //在后台不被系统挂起
        [self.manager setPausesLocationUpdatesAutomatically:NO];
        // ios9以上需要
        [self.manager setAllowsBackgroundLocationUpdates:YES];
        [self.manager startUpdatingLocation];

    }
    return self;
}

#pragma mark -- AMapLocationManagerDelegate 高德定位代理
-  (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    NSLog(@"lat--%.6f,lng--%.6f",location.coordinate.latitude,location.coordinate.longitude);

    coor = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude);

    MACoordinateSpan span = MACoordinateSpanMake(0.01, 0.01);
    CLLocationCoordinate2D coor2 = CLLocationCoordinate2DMake(coor.latitude,coor.longitude);
    
    coor_ = coor2;
    
    MACoordinateRegion region = MACoordinateRegionMake(coor2, span);
    [self.amapView setRegion:region];

    //CLLocationCoordinate2D coor3 = CLLocationCoordinate2DMake(22.566795,113.868113);
    [self addCarBycenterCoordinate:coor2];
    //    //逆地理编码
//    _search = [[AMapSearchAPI alloc]init];
//    _search.delegate = self;
//    AMapReGeocodeSearchRequest * regeo = [[AMapReGeocodeSearchRequest alloc]init];
//
//    regeo.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
//
//    regeo.requireExtension = YES;
//
//    [self.search AMapReGoecodeSearch:regeo];
//    [self.manager stopUpdatingLocation];

}

- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"error--%@",error);
}

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    NSLog(@"response--%@",response.regeocode.formattedAddress);
}

//高德地图移动代理
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    for ( MAAnnotationView *newAnnotation in self.annotations) {
        [newAnnotation removeFromSuperview];
    }

    [self.annotations removeAllObjects];

    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    mapCenterCoor_ = centerCoordinate;

    //逆地理编码

    AMapReGeocodeSearchRequest * regeo = [[AMapReGeocodeSearchRequest alloc]init];

    regeo.location = [AMapGeoPoint locationWithLatitude:centerCoordinate.latitude longitude:centerCoordinate.longitude];

    regeo.requireExtension = YES;

    [self.search AMapReGoecodeSearch:regeo];
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)viewview
{

 NSLog(@"111");
}

- (void)click
{
 NSLog(@"111");

    self.jumpToInfoBlock();
}

//高德返回我的自定义大头针
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{

    static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
    MAAnnotationView*annotationView = (MAAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
    if (annotationView == nil)
    {
        annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
    }
    //返回到我的自定义的大头针
    annotationView.image =[UIImage imageNamed:@"bubbles"];
    annotationView.alpha = 0.8;

    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 13, annotationView.frame.size.width, 15)];
    annotationView.userInteractionEnabled = YES;
    if (self.index == 0) {
        label.text = @"深圳宝安 → 深圳南山";
    }
    if (self.index == 1) {
        label.text = @"黑色奥迪A4L";
    }
    if (self.index == 2) {
        label.text = @"华丰停车场";
    }

    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:13];
    [annotationView addSubview:label];
         annotationView.canShowCallout=YES;

    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(click)];
    [annotationView addGestureRecognizer:tap];
        return annotationView;

}


//添加模拟的车子位置

static NSString *pointAnnotitationIdentifierID = @"Identifier_CJ";

-(void)addCarBycenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
{


    NSUInteger  count =  arc4random_uniform(4);
    count+= 1;

    annitationViewCount_ = count;
    annitationViewCountAoutUp_ = 0;
    for (int i = 0; i < count;  i++) {

        CGFloat  distance_lat = arc4random_uniform(40);
        CGFloat  distance_log = arc4random_uniform(40);


        CLLocationCoordinate2D centerCoordinate1 = CLLocationCoordinate2DMake(centerCoordinate.latitude+distance_lat/10000*(((int)distance_lat%2==1)? -1:1), centerCoordinate.longitude+distance_log/10000*(((int)distance_log%2==1)? -1:1));

        NSLog(@"----%.6f,,,,,,----%.6f",centerCoordinate1.latitude,centerCoordinate1.longitude);
        MAPointAnnotation*pointAnnotitation = [[MAPointAnnotation alloc]init];

        pointAnnotitation.coordinate = centerCoordinate1;

        [_amapView addAnnotation:pointAnnotitation];

    }

    
    
}


@end
